import 'package:fate_blind_box/ui/account/profile_complete_v4.dart';
import 'package:fate_blind_box/ui/guide/download_new.dart';
import 'package:fate_blind_box/ui/login/personinformation/personinformation_zero.dart';
import 'package:fate_blind_box/ui/main/navigator.dart';
import 'package:fate_blind_box/utils/page.dart';
import 'package:fate_blind_box/utils/web.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

import '../../network/Api.dart';
import '../../network/http_config.dart';
import '../../utils/loading.dart';
import '../../utils/provider.dart';
import '../../utils/snack_bar.dart';

class LoginByWechat extends StatelessWidget {
  const LoginByWechat({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const _LoginByWechatState();
  }
}

class _LoginByWechatState extends StatefulWidget {
  const _LoginByWechatState({Key? key}) : super(key: key);

  @override
  State<_LoginByWechatState> createState() => _LoginBindMobStateState();
}

class _LoginBindMobStateState extends State<_LoginByWechatState> {
  late double _screenWidth;
  late double _screenHeight;
  late Size _size;

  @override
  void initState() {
    super.initState();

    if (kIsWeb) {
      _handleWeb();
    } else {}
  }

  _handleWeb() async {
    // var htt = 'https://ahpsvr.anyeoa.com?inviteCoded=eQn2ia';
    // Uri.dataFromString(htt).queryParameters;
    final params = Web.getParams();
    if (params['invite_code']?.isNotEmpty == true) {
      await Provider.cache("invite_coded", params['invite_code']);
      // ThemeSnackBar.show(context, params["invite_code"]);

      print('params');
    }
    final wxCode = await Provider.getCache("code");
    if (wxCode?.isNotEmpty == true) {
      _loginByWechatCode(wxCode);
    }
  }

  void _wechatCallback() {
    toast('点击微信登陆了');
    if (kIsWeb) return;

    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        int? code = res.errCode;
        if (kDebugMode) {
          print('-----------------' + code.toString());
        }
        if (code == 0) {
          Provider.wechatCode = res.code ?? "";
          // Navigator.of(context).push(MaterialPageRoute(builder: (ctx) => const AppMain()));
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (context) => AppMain()),
              (route) => route == null);
        } else {
          toast(res.errStr ?? "微信授权登录失败[${res.errCode}]");
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // _size = MediaQuery.of(context).size;
    // _screenWidth = _size.width;
    // _screenHeight = _size.height;
    // print(_screenWidth);
    return Scaffold(
      body: Column(
        children: [
          // 标题
          Container(
            margin: const EdgeInsets.fromLTRB(20, 130, 0, 0),
            child: const Text(
              "欢迎登录都肆商圈",
              style: TextStyle(fontSize: 30, color: Color(0xFF222222)),
            ),
          ),

          const Expanded(child: SizedBox()),
          // 微信登录、协议
          Align(
            alignment: Alignment.bottomCenter,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                GestureDetector(
                  child: const Image(
                    width: 60,
                    height: 60,
                    image: AssetImage("images/ic_cwx.png"),
                  ),
                  onTap: () {
                    _loginByWechat();
                  },
                ),
                Container(
                  padding: const EdgeInsets.fromLTRB(0, 20, 0, 20),
                  child: const Text('请点击微信登录'),
                ),
                Container(
                    padding: const EdgeInsets.fromLTRB(0, 130, 0, 20),
                    child: Text.rich(TextSpan(children: [
                      const TextSpan(
                          text: "登录代表您已同意",
                          style: TextStyle(
                              color: Color(0xFF222222), fontSize: 12)),
                      TextSpan(
                        text: "《用户协议》",
                        style: const TextStyle(
                            color: Color(0xFF222222), fontSize: 12),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            print('用户协议');
                          },
                      ),
                      TextSpan(
                        text: "、《隐私政策》",
                        style: const TextStyle(
                            color: Color(0xFF222222), fontSize: 12),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            print('隐私政策');
                          },
                      )
                    ])))
              ],
            ),
          )
        ],
      ),
    );
  }

  _loginByWechat() async {
    if (kIsWeb) {
      final redirectUrl = Uri.encodeComponent("https://ahpsvr.anyeoa.com/");
      final url =
          'https://open.weixin.qq.com/connect/oauth2/authorize?appid=${Provider.wechatAppID}&redirect_uri=$redirectUrl&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
      print('-------------------------' + url);
      // await launch(url);
      Web.reload(url);
    } else {
      fluwx.sendWeChatAuth(
          scope: "snsapi_userinfo", state: 'wechat_sdk_demo_test');

      _wechatCallback();
    }
  }

  bool _isCompleteInfo(user) {
    return user['bornDate']?.toString().isNotEmpty == true;
  }

  bool _isBindingMob(user) {
    String mobilePhone = '';
    if (user["mobilePhone"] != null) {
      mobilePhone = user["mobilePhone"]?.toString() ?? '';
    }
    return mobilePhone.isNotEmpty ? true : false;
  }

  _loginByWechatCode(String? code) {
    if (code?.isNotEmpty != true) {
      return;
    }
    loading(() async {
      final res = await Api.getInstance().wechatLogin(code!);
      await Provider.remove("code");
      await Provider.remove("state");
      if (res['code'] == 0 && res['data'] != null) {
        final data = res['data'];
        Provider.memberId = data['id'];
        Provider.nickName = data['nickName'];
        // Provider.userEaseName = data['emUser']['username'];
        Provider.memberId = data['id'];
        Provider.profilePhoto = data['profilePhoto'];
        Provider.memberInfo = data;
        HttpConfig.token = data['token'];
        await Provider.cache("memberId", Provider.memberId);
        await Provider.cache("token", HttpConfig.token);
        await Provider.cache("username", Provider.userEaseName);
        String? inviteCode = await Provider.getCache("invite_code");
        if (inviteCode?.isNotEmpty == true) {
          await Api.getInstance().invite(Provider.memberId, inviteCode!);
          if (_isBindingMob(data)) {
            Navigate.toPage(const ProfileCompleteV4Ui());
          } else {
            Navigate.toPage(const PersonInformationZeroPageWidget('微信'));
          }
        } else if (_isCompleteInfo(data)) {
          Navigate.toPage(const DownloadAppUiNew());
        } else {
          Navigate.toMain();
        }
      } else if (res['code'] != 500 && res['data'] != null) {
        toast("服务器开小差了-_-!");
      } else {
        ThemeSnackBar.show(context, res.toString());
      }
    });
  }
}
